import { createRouter, createWebHistory } from 'vue-router';
import type { RouteRecordRaw } from 'vue-router';

// 路由配置数组
const routes: RouteRecordRaw[] = [
  {
    path: '/',
    redirect: '/login'
  },
  {
    path: '/login',
    name: 'Login',
    component: () => import('../views/Login.vue'),
    meta: { title: '登录' }
  },
  {
    path: '/register',
    name: 'Register',
    component: () => import('../views/Register.vue'),
    meta: { title: '注册' }
  },
  {
    path: '/home',
    name: 'Home',
    component: () => import('../views/Home.vue'),
    meta: { title: '首页', requiresAuth: true },
    children: [
      {
        path: 'dashboard',
        name: 'Dashboard',
        component: () => import('../views/Dashboard.vue'),
        meta: { title: '仪表盘' }
      },
      {
        path: 'health',
        name: 'HealthData',
        component: () => import('../views/Dashboard.vue'), // 临时使用Dashboard组件
        meta: { title: '健康数据' }
      },
      {
        path: 'emergency',
        name: 'EmergencyCall',
        component: () => import('../views/Dashboard.vue'), // 临时使用Dashboard组件
        meta: { title: '紧急呼叫' }
      },
      {
        path: 'service',
        name: 'ServiceAppointment',
        component: () => import('../views/Dashboard.vue'), // 临时使用Dashboard组件
        meta: { title: '服务预约' }
      },
      {
        path: 'profile',
        name: 'UserProfile',
        component: () => import('../views/Dashboard.vue'), // 临时使用Dashboard组件
        meta: { title: '个人信息' }
      }
    ]
  },
  {
    path: '/:pathMatch(.*)*',
    name: 'NotFound',
    component: () => import('../views/NotFound.vue'),
    meta: { title: '404' }
  }
];

// 创建路由实例
const router = createRouter({
  history: createWebHistory(),
  routes
});

// 路由前置守卫
router.beforeEach((to, _from, next) => {
  // 设置页面标题
  document.title = to.meta.title as string || '智能养老管理系统';
  
  // 检查是否需要认证
  const requiresAuth = to.meta.requiresAuth;
  const token = localStorage.getItem('token');
  
  if (requiresAuth && !token) {
    // 需要认证但没有token，重定向到登录页
    next('/login');
  } else {
    // 允许通过
    next();
  }
});

export default router;